﻿using AutoMapper;
using BW.MesProject.Public.ErrorCode;
using BW.MesProject.Public.Infrastructure;
using BW.MesProject.WareHouse.Domain;
using BW.MesProject.WareHouse.Infrastructure;
using BW.MesProject.WareHouse.Infrastructure.Dto.Input;
using BW.MesProject.WareHouse.Infrastructure.Dto.OutPut;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing.Drawing2D;
using System.Drawing.Printing;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Yitter.IdGenerator;
using static Dm.net.buffer.ByteArrayBuffer;

namespace BW.MesProject.WareHouse.Application
{
    public class WareHouseServices : IWareHouseServices
    {
        private readonly IBaseRepository<WarehouseModel> _WareHouse;
        private readonly IBaseRepository<EMPModel> _Emp;
        private readonly IBaseRepository<WareHouseTypeModel> _WareHouseType;
        private readonly IMapper _mapper;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="WareHouse"></param>
        /// <param name="EmpModel"></param>
        /// <param name="WareHouseType"></param>
        /// <param name="mapper"></param>
        public WareHouseServices(IBaseRepository<WarehouseModel> WareHouse, IBaseRepository<EMPModel> EmpModel, IBaseRepository<WareHouseTypeModel> WareHouseType, IMapper mapper)
        {
            _WareHouse = WareHouse;
            _Emp = EmpModel; // 允许为空，但在使用时会进行检查
            _WareHouseType = WareHouseType; // 允许为空，但在使用时会进行检查
            this._mapper = mapper;
        }
        /// <summary>
        /// 新增仓库
        /// </summary>
        /// <param name="WareModel"></param>
        /// <returns></returns>
        public ApiResult<int> AddWareHouse(WarehouseModel WareModel)
        {


            //判断仓库编码，名称。类型、仓管员是否为空
            if (string.IsNullOrEmpty(WareModel.Warehouseid) || string.IsNullOrEmpty(WareModel.Warehousename) || string.IsNullOrEmpty(WareModel.WHTypeId) || string.IsNullOrEmpty(WareModel.Warehouseempid))
            {
                return new ApiResult<int>()
                {
                    Code = ApiEnums.Fail,
                    Message = "请检查仓库的编号、名称、类型与管理员是否为空"
                };
            }
            var model = _WareHouse.GetValue(x => x.Warehouseid == WareModel.Warehouseid);
            if (model != null && !string.IsNullOrEmpty(model.Warehouseid))
            {
                return new ApiResult<int>()
                {
                    Code = ApiEnums.Fail,
                    Message = "仓库编号重复，请重新检查修改！！！"
                };
            }
            model = _WareHouse.GetValue(x => x.Warehousename == WareModel.Warehousename);
            if (model != null && !string.IsNullOrEmpty(model.Warehousename))
            {
                return new ApiResult<int>()
                {
                    Code = ApiEnums.Fail,
                    Message = "仓库名称重复，请重新检查修改！！！"
                };
            }
            //long aa = YitIdHelper.NextId();
            WareModel.WHId = YitIdHelper.NextId();
            //添加
            var models = _mapper.Map<WarehouseModel>(WareModel);

            return new ApiResult<int>
            {
                Code = ApiEnums.Success,
                Message = "添加成功",
                Data = _WareHouse.Add(WareModel),
            };
        }



        ///// <summary>
        ///// 查询仓库
        ///// </summary>
        ///// <param name="WareName">仓库名称（可选）</param>
        ///// <param name="pagesize">每页数量（0表示不分页）</param>
        ///// <param name="pageNum">页码</param>
        ///// <returns>仓库列表</returns>
        //public ApiResult<List<WarehouseModel>> GetWareHouse(string? WareName, int pagesize, int pageNum)
        //{
        //    int totalCount = 0;

        //    try
        //    {
        //        // 获取所有仓库
        //        var list = _WareHouse.GetAll();
        //        List<WarehouseModel> WHlist = new List<WarehouseModel>();

        //        // 根据是否需要分页处理数据
        //        if (pagesize == 0)
        //        {
        //            // 不分页，仅按名称筛选
        //            if (WareName != null)
        //            {
        //                WHlist = list.Where(x => x.Warehousename.Contains(WareName)).OrderBy(u => u.CreatedTime).ToList();
        //            }
        //            else
        //            {
        //                WHlist = list.OrderBy(u => u.CreatedTime).ToList();
        //            }
        //        }
        //        else
        //        {
        //            // 分页查询
        //            if (WareName != null)
        //            {
        //                WHlist = list.Where(x => x.Warehousename.Contains(WareName)).OrderBy(u => u.CreatedTime).ToPageList(pageNum, pagesize, ref totalCount).ToList();
        //            }
        //            else
        //            {
        //                WHlist = list.OrderBy(u => u.CreatedTime).ToPageList(pageNum, pagesize, ref totalCount).ToList();
        //            }
        //        }

        //        // 初始化空列表，避免null引用
        //        List<EMPModel> EmpList = new List<EMPModel>();
        //        List<WareHouseTypeModel> WHTypeList = new List<WareHouseTypeModel>();

        //        // 处理结果数据
        //        var result = new List<WarehouseModel>();

        //        // 如果有仓库数据，才去查询员工和仓库类型
        //        if (WHlist.Count > 0)
        //        {
        //            try
        //            {
        //                // 只有在需要时才查询员工和仓库类型数据
        //                if (_Emp != null && WHlist.Any(w => !string.IsNullOrEmpty(w.Warehouseempid)))
        //                {
        //                    EmpList = _Emp.GetAll()?.ToList() ?? new List<EMPModel>();
        //                }

        //                if (_WareHouseType != null && WHlist.Any(w => !string.IsNullOrEmpty(w.Warehousetype)))
        //                {
        //                    WHTypeList = _WareHouseType.GetAll()?.ToList() ?? new List<WareHouseTypeModel>();
        //                }
        //            }
        //            catch (Exception ex)
        //            {
        //                Console.WriteLine($"查询关联数据时发生异常: {ex.Message}");
        //                // 继续使用空列表
        //            }
        //        }

        //        foreach (var order in WHlist)
        //        {
        //            // 创建新对象，避免修改原始数据
        //            var newWarehouse = new WarehouseModel
        //            {
        //                WareId = order.WareId,
        //                Warehouseid = order.Warehouseid,
        //                Warehousename = order.Warehousename,
        //                Warehousetype = order.Warehousetype, // 暂存原始类型ID
        //                Warehouseempid = order.Warehouseempid, // 暂存原始员工ID
        //                Address = order.Address,
        //                Memo = order.Memo,
        //                CreatedTime = order.CreatedTime,
        //                CreatedBy = order.CreatedBy,
        //                UpdatedTime = order.UpdatedTime
        //            };

        //            // 处理仓库类型，关联WareHouseTypeModel表
        //            if (!string.IsNullOrEmpty(order.Warehousetype) && WHTypeList.Count > 0)
        //            {
        //                var warehouseType = WHTypeList.FirstOrDefault(t => t.WHTypeId == order.Warehousetype);
        //                if (warehouseType != null)
        //                {
        //                    // 将类型名称替换原始类型ID
        //                    newWarehouse.Warehousetype = warehouseType.WHTypeName;
        //                }
        //            }

        //            // 处理仓管员ID，通过逗号分割，关联EMPModel表查询
        //            if (!string.IsNullOrEmpty(order.Warehouseempid) && EmpList.Count > 0)
        //            {
        //                try
        //                {
        //                    // 分割仓管员ID
        //                    var empIds = order.Warehouseempid
        //                        .Split(',', StringSplitOptions.RemoveEmptyEntries)
        //                        .Select(id => id.Trim())
        //                        .ToList();

        //                    // 获取关联员工信息
        //                    var relatedEmps = EmpList
        //                        .Where(p => empIds.Contains(p.EMPID))
        //                        .ToList();

        //                    // 以 "(empid)EMPName" 格式重新组合员工信息，用逗号分隔
        //                    if (relatedEmps.Count > 0)
        //                    {
        //                        var formattedEmpInfo = string.Join(", ", relatedEmps.Select(p => $"({p.EMPID}){p.EMPName}"));

        //                        // 将格式化后的员工信息替换原始员工ID
        //                        newWarehouse.Warehouseempid = formattedEmpInfo;
        //                    }
        //                }
        //                catch (Exception ex)
        //                {
        //                    Console.WriteLine($"处理员工信息时发生异常: {ex.Message}");
        //                    // 保留原始员工ID
        //                }
        //            }

        //            result.Add(newWarehouse);
        //        }

        //        return new ApiResult<List<WarehouseModel>>()
        //        {
        //            Code = ApiEnums.Success,
        //            Message = "查询成功",
        //            Data = result,
        //            TotalCount = totalCount,
        //            PageNum = pageNum,
        //            PageSize = pagesize
        //        };
        //    }
        //    catch (Exception ex)
        //    {
        //        Console.WriteLine($"查询仓库信息时发生异常: {ex.Message}");
        //        return new ApiResult<List<WarehouseModel>>()
        //        {
        //            Code = ApiEnums.Fail,
        //            Message = $"查询失败: {ex.Message}",
        //            Data = new List<WarehouseModel>(),
        //            TotalCount = 0,
        //            PageNum = pageNum,
        //            PageSize = pagesize
        //        };
        //    }
        //}

        /// <summary>
        /// 查询仓库
        /// </summary>
        /// <param name="qryInput">查询出入的值</param>
        /// <returns></returns>
        public ApiResult<List<WareHouseOut>> GetWareHouse(QryInput qryInput)
        {
            int totalCount = 0;

            try
            {
                // 获取所有仓库
                var list = _WareHouse.GetAll().Where(x => x.IsDeleted == false);

                // 根据是否需要分页处理数据
                if (qryInput.PageSize == 0)
                {
                    list = list.Where(x => x.IsEnable == true).OrderBy(u => u.CreatedTime);
                }
                else
                {
                    // 按编码查询
                    if (!string.IsNullOrEmpty(qryInput.QryID) && !string.IsNullOrEmpty(qryInput.QryName))
                    {
                        list = list.Where(x => x.Warehouseid.Contains(qryInput.QryID) && x.Warehousename.Contains(qryInput.QryName));
                    }
                    else if (!string.IsNullOrEmpty(qryInput.QryID))
                    {
                        list = list.Where(x => x.Warehouseid.Contains(qryInput.QryID));
                    }
                    else if (!string.IsNullOrEmpty(qryInput.QryName))
                    {
                        list = list.Where(x => x.Warehousename.Contains(qryInput.QryName));
                    }
                }

                // 初始化空列表，避免null引用
                List<EMPModel> EmpList = new List<EMPModel>();
                List<WareHouseTypeModel> WHTypeList = new List<WareHouseTypeModel>();

                // 如果有仓库数据，才去查询员工和仓库类型
                if (list.Count() > 0)
                {
                    try
                    {
                        // 只有在需要时才查询员工和仓库类型数据
                        if (_Emp != null)
                        {
                            EmpList = _Emp.GetAll()?.ToList() ?? new List<EMPModel>();
                        }

                        if (_WareHouseType != null)
                        {
                            WHTypeList = _WareHouseType.GetAll()?.ToList() ?? new List<WareHouseTypeModel>();
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"查询关联数据时发生异常: {ex.Message}");
                        // 继续使用空列表
                    }
                }

                // 处理结果数据
                var result = new List<WareHouseOut>();

                // 联表查询设备类型，获取设备类型名称等信息
                var query1 = list.LeftJoin<WareHouseTypeModel>((a, b) => a.WHTypeId == b.WHTypeId).LeftJoin<EMPModel>((a, b, c) => a.CreatedBy == c.EMPID).Select((a, b, c) =>
                     new WareHouseOut
                     {
                         WHId = a.WHId,//主键ID
                         Warehouseid = a.Warehouseid,//仓库ID
                         Warehousename = a.Warehousename,//仓库名称
                         WHTypeId = b.WHTypeId,//仓库类型编码
                         WHTypeName = b.WHTypeName,//仓库类型名称
                         Address = a.Address,//地址
                         Memo = a.Memo,//描述
                         Warehouseempid = a.Warehouseempid, // 保存原始员工ID以便后续处理
                         EMPID = c.EMPID,
                         EMPName = c.EMPName,
                         CreatedBy = a.CreatedBy,
                         CreatedTime = a.CreatedTime,
                         UpdatedTime = a.UpdatedTime,
                         IsEnable=a.IsEnable,
                         IsDeleted=a.IsDeleted
                     });

                var queryList = query1?.ToList();

                for (int i = 0; i < queryList.Count(); i++)
                {
                    if (!string.IsNullOrEmpty(queryList[i].Warehouseempid) && EmpList.Count > 0)
                    {
                        try
                        {

                            // 分割仓管员ID
                            var empIds = queryList[i].Warehouseempid
                                .Split(',', StringSplitOptions.RemoveEmptyEntries)
                                .Select(id => id.Trim())
                                .ToList();

                            // 获取关联员工信息
                            var relatedEmps = EmpList
                                .Where(p => empIds.Contains(p.EMPID))
                                .ToList();

                            // 如果有关联员工，取第一个作为主要员工
                            if (relatedEmps.Count > 0)
                            {
                                // 如果有多个员工，可以考虑在备注中添加其他员工信息
                                if (relatedEmps.Count > 1)
                                {
                                    var otherEmps = string.Join(", ", relatedEmps.Select(p => $"({p.EMPID}){p.EMPName}"));
                                    //var otherEmps = string.Join(", ", relatedEmps.Skip(1).Select(p => $"({p.EMPID}){p.EMPName}"));
                                    //queryList[i].Warehouseempid = otherEmps string.IsNullOrEmpty(queryList[i].Memo)
                                    //    ? $"其他仓管员: {otherEmps}"
                                    //    : $"{queryList[i].Memo}; 其他仓管员: {otherEmps}";
                                    queryList[i].Warehouseempid = otherEmps;
                                }
                            }
                            else
                            {
                                // 如果找不到员工，至少保留员工ID
                                queryList[i].Warehouseempid = queryList[i].Warehouseempid;
                            }
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine($"处理员工信息时发生异常: {ex.Message}");
                            // 保留原始员工ID
                            queryList[i].Warehouseempid = queryList[i].Warehouseempid;
                        }
                    }
                }

                // 计算总数量
                totalCount = queryList.Count();

                // 分页处理
                if (qryInput.PageSize > 0)
                {
                    queryList = queryList
                        .OrderBy(a => a.Warehouseid).ThenBy(x => x.CreatedTime)
                        .Skip((qryInput.PageNum - 1) * qryInput.PageSize)
                        .Take(qryInput.PageSize)
                        .ToList();
                }

                return new ApiResult<List<WareHouseOut>>()
                {
                    Code = ApiEnums.Success,
                    Message = "查询成功",
                    Data = queryList,
                    TotalCount = totalCount,
                    PageNum = qryInput.PageNum,
                    PageSize = qryInput.PageSize
                };
            }
            catch (Exception ex)
            {
                Console.WriteLine($"查询仓库信息时发生异常: {ex.Message}");
                return new ApiResult<List<WareHouseOut>>()
                {
                    Code = ApiEnums.Fail,
                    Message = $"查询失败: {ex.Message}",
                    Data = new List<WareHouseOut>(),
                    TotalCount = 0,
                    PageNum = qryInput.PageNum,
                    PageSize = qryInput.PageSize
                };
            }
        }

        /// <summary>
        /// 修改仓库
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ApiResult<int> UpdateWareHouse(WarehouseModel model)
        {
            //根据id查询是否有这条数据没有就修改不了
            var query = _WareHouse.GetValue(x => x.WHId == model.WHId);
            if (query == null)
            {
                return new ApiResult<int>()
                {
                    Code = ApiEnums.Fail,
                    Message = "修改失败",
                    Data = 0,
                    TotalCount = 0
                };
            }
            //model.CreatedTime = DateTime.Now;
            //model.UpdatedTime = DateTime.Now;
            //保存添加人和添加时间，添加修改人和修改时间
            _WareHouse.Update(model);
            return new ApiResult<int>()
            {
                Code = ApiEnums.Success,
                Message = "修改成功",
                Data = 1,
                TotalCount = 0
            };
            //使用修改方法修改成功

        }
        /// <summary>
        /// 删除仓库
        /// </summary>
        /// <param name="Id">仓库主键ID</param>
        /// <returns>操作结果</returns>
        public ApiResult<int> DeleteWareHouse(long Id)
        {
            // 参数验证
            if (Id == 0)
            {
                return new ApiResult<int>()
                {
                    Code = ApiEnums.Fail,
                    Message = "无效的仓库ID",
                    Data = 0,
                    TotalCount = 0
                };
            }

            try
            {
                // 根据id查询仓库信息
               var model = _WareHouse.GetValue(x => x.WHId == Id);

                // 检查是否存在
                if (model == null)
                {
                    return new ApiResult<int>()
                    {
                        Code = ApiEnums.Fail,
                        Message = "未找到指定的仓库信息",
                        Data = 0,
                        TotalCount = 0
                    };
                }

                // 删除前检查是否有关联的货架等信息
                // TODO: 如果有其他关联表，需要检查是否有关联数据

                // 执行删除操作
                int result = _WareHouse.Delete(model);

                if (result > 0)
                {
                    return new ApiResult<int>()
                    {
                        Code = ApiEnums.Success,
                        Message = "删除成功",
                        Data = result,
                        TotalCount = 0
                    };
                }
                else
                {
                    return new ApiResult<int>()
                    {
                        Code = ApiEnums.Fail,
                        Message = "删除失败",
                        Data = 0,
                        TotalCount = 0
                    };
                }
            }
            catch (Exception ex)
            {
                // 记录异常信息
                Console.WriteLine($"删除仓库时发生异常: {ex.Message}");

                return new ApiResult<int>()
                {
                    Code = ApiEnums.Fail,
                    Message = $"删除失败: {ex.Message}",
                    Data = 0,
                    TotalCount = 0
                };
            }
        }

        /// <summary>
        /// 修改启用
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ApiResult<int> UpdateEnable(WarehouseModel model)
        {
            var IsEnable = model.IsEnable;
            model = _WareHouse.GetValue(x => x.WHId == model.WHId);
            model.IsEnable = IsEnable;
            var Message = string.Empty;
            if (IsEnable)
            {
                Message = "启用成功";
            }
            else
            {
                Message = "停用成功";
            }
            return new ApiResult<int>()
            {
                Code = ApiEnums.Success,
                Message = Message,
                Data = _WareHouse.Update(model),
                TotalCount = 0
            };
        }

        /// <summary>
        /// 软删除（修改状态）
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public ApiResult<int> UpdateDelete(long Id)
        {
            ////根据id修改逻辑删除为 false
            //model = _WareHouse.GetValue(x => x.WHId == model.WHId);
            //model.IsDeleted = true;
            //return new ApiResult<int>()
            //{
            //    Code = ApiEnums.Success,
            //    Message = "删除成功",
            //    Data = _WareHouse.Update(model),
            //    TotalCount = 0
            //};
            //根据id修改逻辑删除为 false
           var model = _WareHouse.GetValue(x => x.WHId == Id);
            model.IsDeleted = true;
            return new ApiResult<int>()
            {
                Code = ApiEnums.Success,
                Message = "删除成功",
                Data = _WareHouse.Update(model),
                TotalCount = 0
            };
        }

        /// <summary>
        /// 查询表是否有该编码
        /// </summary>
        /// <param name="Warehouseid"></param>
        /// <returns></returns>
        public ApiResult<int> GetWareHouseID(string Warehouseid)
        {
           var model = _WareHouse.GetValue(x => x.Warehouseid == Warehouseid);
            return new ApiResult<int>()
            {
                Code = ApiEnums.Success,
                Message = "成功",
                Data = 1,
                TotalCount = 0
            };

        }
    }
}
